import { findCartList, mergeLocalCart, insertCart, deleteCart, updateCart, checkAllCart } from '@/api/cart'
export default {
  namespaced: true,
  state: () => ({
    list: []
  }),
  getters: {
    // 有效商品
    validLis (state) {
      return state.list.filter(item => item.isEffective)
    },
    // 有效商品选中的商品
    validSeled (state, getters) {
      return getters.validLis.filter(item => item.selected)
    },
    // 有效商品选中的商品总价价格
    validSeledTotal (state, getters) {
      return getters.validSeled.reduce((pre, item) => {
        return (pre += item.count * item.nowPrice)
      }, 0)
    },
    // 有效商品列表是否是全部选中状态
    isAll (state, getters) {
      return getters.validLis.every(item => {
        return item.selected
      })
    }

  },
  mutations: {
    inserCart (state, goods) {
      const sameIndex = state.list.findIndex(item => {
        return item.skuId === goods.skuId
      }
      )
      console.log(sameIndex)
      if (sameIndex > -1) {
        state.list[sameIndex].count += goods.count
      } else {
        state.list.unshift(goods)
      }
    },
    // 单选
    singleCheck (state, { good, sel }) {
      console.log(good)
      const currGood = state.list.find(item => item.skuId === good.skuId)
      currGood.selected = sel
    },
    // 全选
    allCheck (state, sel) {
      state.list.forEach(ele => {
        ele.selected = sel
      })
    },
    // 删除
    delCart (state, good) {
      const i = state.list.findIndex(item => item.skuId === good.skuId)
      state.list.splice(i, 1)
    },
    // 数量
    setCount (state, { good, newCount }) {
      const id = state.list.find(item => item.skuId === good.skuId)
      id.count = newCount
    },
    // 储存后台购物出数据
    setList (state, list) {
      state.list = list
    }

  },
  actions: {
    /**
        * 加入购物车action
        * 思路：区分是否登录=》1. 未登录，直接调用addCart存本地 2. 登陆了，调用接口存到数据库
        * @param {*} param{commit, rootState获取其它模块的state变量}
        * @param {*} good 当前加入list商品数据
        */
    async addCartAction ({ commit, rootState, dispatch }, good) {
      console.log(rootState)
      if (rootState.user.profile.token) {
        // 已经登录（调用接口存到数据库）
        const res = await insertCart({ skuId: good.skuId, count: good.count })
        console.log(res)
        dispatch('getListAction')
      } else {
        // 没有登录
        commit('inserCart', good)
      }
    },
    // 单选
    async singleCheckAction ({ commit, rootState, dispatch }, { good, sel }) {
      if (rootState.user.profile.token) {
        // 已经登录（调用接口存到数据库）
        const res = await updateCart({ skuId: good.skuId, selected: sel, count: good.count })
        console.log(res)
        dispatch('getListAction')
      } else {
        // 没有登录
        console.log(good)
        commit('singleCheck', { good, sel })
      }
    },
    // 全选
    async allCheckAction ({ commit, rootState, dispatch, getters }, sel) {
      if (rootState.user.profile.token) {
        const ids = getters.validLis.map(item => item.skuId)
        await checkAllCart({ selected: sel, ids: ids })
        dispatch('getListAction')
      } else {
        commit('allCheck', sel)
      }
    },
    // 删除
    async delCartAction ({ commit, dispatch, rootState }, sel) {
      if (rootState.user.profile.token) {
        // console.log(sel)
        await deleteCart([sel.skuId])
        dispatch('getListAction')
      } else {
        commit('delCart', sel)
      }
    },
    // 数量
    async setCountAction ({ commit, rootState, dispatch }, { good, newCount }) {
      if (rootState.user.profile.token) {
        await updateCart({ skuId: good.skuId, selected: good.selected, count: newCount })
        dispatch('getListAction')
      } else {
        commit('setCount', { good, newCount })
      }
    },
    // 获取登陆后的购物车
    async getListAction ({ commit }) {
      const { result } = await findCartList()
      console.log(result)
      commit('setList', result)
    },

    // 登录合并本地购物车
    async mergeLocalCart (ctx) {
      // 判断本地购物车是否需要合并
      if (ctx.state.list.length) {
        // 存储token后调用合并API接口函数进行购物合并
        const cartList = ctx.state.list.map(({ skuId, lected, count }) => {
          return { skuId, lected, count }
        })
        await mergeLocalCart(cartList)
        // 调用接口获取合并后最新的购物车数据
      }
      // 如果本地没有,也要获取
      ctx.dispatch('getListAction')
    }
  }
}
